package org.nf.web.initializer;

import jakarta.servlet.DispatcherType;
import jakarta.servlet.FilterRegistration;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import org.nf.web.WebApplicationInitializer;
import org.nf.web.config.Configure;
import org.nf.web.config.MvcConfig.CharacterEncodingConfig;
import org.nf.web.filter.CharacterEncodingFilter;
import java.util.EnumSet;

public class CharacterEncodingFilterInitializer implements WebApplicationInitializer {

    private final static String FILTER_NAME = "encoding";
    private final static String URL_PATTERN = "/*";

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        initCharacterEncodingFilter(servletContext);
    }

    private void initCharacterEncodingFilter(ServletContext servletContext) {
        Configure config = (Configure) servletContext.getAttribute(Configure.class.getName());
        CharacterEncodingConfig encodingConfig = config.getMvc().getEncoding();
        if(encodingConfig.getEnable()) {
            CharacterEncodingFilter filter = new CharacterEncodingFilter();
            filter.setEncoding(encodingConfig.getCharset());
            filter.setForceEncoding(encodingConfig.getForce());
            filter.setForceRequestEncoding(encodingConfig.getForceRequest());
            filter.setForceResponseEncoding(encodingConfig.getForceResponse());
            FilterRegistration.Dynamic registration = servletContext.addFilter(FILTER_NAME, filter);
            registration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, URL_PATTERN);
        }
    }
}
